<template>
  <div class="news-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/industry-belt' }">产业带</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/industry-belt', query: { tab: 'news' } }">行业新闻</el-breadcrumb-item>
            <el-breadcrumb-item>{{ newsData?.title || '新闻详情' }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>
    </div>

    <!-- 新闻内容 -->
    <div class="news-content" v-if="!loading && newsData">
      <div class="container">
        <div class="news-main">
          <!-- 新闻标题 -->
          <h1 class="news-title">{{ newsData.title }}</h1>

          <!-- 元信息 -->
          <div class="news-meta">
            <div class="meta-left">
              <span class="date">
                <el-icon class="date-icon"><Calendar /></el-icon> {{ formatDate(newsData.publishDate) }}
              </span>
            </div>
            <div class="meta-right">
              <span class="views">
                <el-icon><View /></el-icon> {{ newsData.views || 0 }} 阅读
              </span>
              <!-- <span class="likes">
                <el-icon><Star /></el-icon> {{ newsData.likes || 0 }} 点赞
              </span>
              <span class="collects">
                <el-icon><Collection /></el-icon> {{ newsData.collects || 0 }} 收藏
              </span> -->
            </div>
          </div>

          <!-- 封面图片 -->
          <div class="news-cover" v-if="newsData.coverImageUrl">
            <img :src="newsData.coverImageUrl" />
          </div>

          <!-- 摘要 -->
          <div class="news-summary" v-if="newsData.summary">
            <h3>摘要</h3>
            <p>{{ newsData.summary }}</p>
          </div>

          <!-- 详细内容 -->
          <div class="news-body" v-html="newsData.content"></div>

          <!-- 标签 -->
          <div class="news-tags" v-if="newsData.tags && newsData.tags.length > 0">
            <h3>标签</h3>
            <div class="tags-list">
              <span v-for="tag in newsData.tags" :key="tag.id" class="tag">{{ tag.tagName }}</span>
            </div>
          </div>
        </div>

        <!-- 侧边栏 -->
        <div class="news-sidebar">
          <!-- 相关新闻 -->
          <div class="related-news">
            <h3>相关新闻</h3>
            <div class="related-list">
              <div
                v-for="item in relatedNews"
                :key="(item as any).id"
                class="related-item"
                @click="goToNews((item as any).id)"
              >
                <h4>{{ (item as any).title }}</h4>
                <span class="related-date">{{ formatDate((item as any).publishDate) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="新闻不存在或已被删除">
        <el-button type="primary" @click="() => navigateTo('/industry-belt?tab=news')">返回列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Calendar, View } from '@element-plus/icons-vue'
import { industryBeltApi } from '~/server/industryBeltApi'
import { useIndustryBeltStore } from '~/stores/industryBelt'
import { ElMessage } from 'element-plus'

// 获取路由参数
const route = useRoute()
const newsId = route.params.id as string

// 响应式数据
const loading = ref(true)
const newsData = ref<any>(null)
const relatedNews = ref<any[]>([])
const industryStore = useIndustryBeltStore()

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 清洗URL
const normalizeUrl = (url: any): string => {
  if (!url) return ''
  if (typeof url !== 'string') return ''
  return url.replace(/[`]/g, '').trim()
}

// 标签数组化
const toTagArray = (tags: any): Array<{ id: number; tagName: string; status: any; createTime: any }> => {
  if (Array.isArray(tags)) return tags
  if (typeof tags === 'string' && tags.trim()) {
    return tags
      .split(',')
      .map((t: string, i: number) => ({ id: i + 1, tagName: t.trim(), status: undefined, createTime: undefined }))
  }
  return []
}

// 映射会议新闻结构
const mapConferenceNews = (raw: any) => ({
  id: raw?.id ?? 0,
  title: raw?.title ?? '',
  summary: raw?.news ?? raw?.description ?? '',
  publishDate: raw?.conferenceDate ?? raw?.updateTime ?? '',
  coverImageUrl: normalizeUrl(raw?.coverImageUrl),
  content: raw?.newsContent ?? '',
  views: 0,
  likes: 0,
  collects: 0,
  tags: toTagArray(raw?.tags),
})

// 获取新闻详情（优先使用列表页缓存，其次用新闻列表查找，不再调用详情接口）
const fetchNewsDetail = async () => {
  try {
    loading.value = true
    const idNum = Number(newsId)
    // 1) 先从 Pinia 缓存读取
    const cached = industryStore.getNewsById(idNum) || industryStore.currentNews
    if (cached && cached.id === idNum) {
      newsData.value = cached
      return
    }
    // 2) 再从新闻列表接口查找并映射
    const response = await industryBeltApi.content.getList({ contentType: 'NEWS', pageNum: 1, pageSize: 200 })
    const list = Array.isArray(response?.list) ? response.list : []
    const found = list.find((item: any) => item.id === idNum)
    if (found) {
      const mapped = mapConferenceNews(found)
      newsData.value = mapped
      industryStore.setCurrentNews(mapped)
    } else {
      newsData.value = null
    }
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    const errorMessage = error?.toString() || ''
    if (errorMessage.includes('401') || errorMessage.includes('402') || errorMessage.includes('登录')) {
      ElMessage.warning('请先登录后再查看新闻详情')
    } else {
      ElMessage.error('获取新闻详情失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 获取相关新闻（映射为统一结构）
const fetchRelatedNews = async () => {
  try {
    const response = await industryBeltApi.content.getList({ contentType: 'NEWS', pageNum: 1, pageSize: 20 })
    const list = Array.isArray(response?.list) ? response.list : []
    relatedNews.value = list
      .filter((item: any) => item.id !== Number(newsId))
      .slice(0, 5)
      .map((item: any) => mapConferenceNews(item))
  } catch (error) {
    console.error('获取相关新闻失败:', error)
    const errorMessage = error?.toString() || ''
    if (errorMessage.includes('401') || errorMessage.includes('402') || errorMessage.includes('登录')) {
      console.warn('相关新闻需要登录才能查看')
    }
  }
}

// 跳转到其他新闻
const goToNews = (id: any) => {
  navigateTo(`/industry-belt/news/${id}`)
}

// 页面加载时获取数据
onMounted(() => {
  fetchNewsDetail()
  fetchRelatedNews()
})

// SEO优化
useHead({
  title: computed(() => newsData.value?.title || '新闻详情'),
  meta: [
    {
      name: 'description',
      content: computed(() => newsData.value?.summary || ''),
    },
  ],
})
</script>

<style scoped lang="scss">
.news-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 15px 0;

  .container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .breadcrumb {
    width: 100%;
  }
}

.news-content {
  padding: 30px 0;

  .container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 30px;
  }
}

.news-main {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .news-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin: 0 0 20px 0;
    line-height: 1.4;
  }

  .news-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;

    .meta-left {
      .date {
        display: flex;
        align-items: center;
        color: #999;
        font-size: 14px;

        .date-icon {
          color: #999;
          margin-right: 1px;
        }
      }
    }

    .meta-right {
      display: flex;
      gap: 20px;
      align-items: center;

      span {
        display: flex;
        align-items: center;
        color: #666;
        font-size: 14px;

        .el-icon {
          margin-right: 4px;
          color: #999;
        }
      }
    }
  }

  .news-cover {
    margin-bottom: 30px;
    text-align: center;

    img {
      max-width: 100%;
      height: auto;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .news-summary {
    margin-bottom: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #1890ff;

    h3 {
      margin: 0 0 15px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 16px;
      line-height: 1.6;
    }
  }

  .news-body {
    margin-bottom: 30px;
    line-height: 1.8;
    color: #333;
    font-size: 16px;

    :deep(h1),
    :deep(h2),
    :deep(h3),
    :deep(h4),
    :deep(h5),
    :deep(h6) {
      margin: 30px 0 15px 0;
      color: #333;
      font-weight: 600;
    }

    :deep(p) {
      margin: 15px 0;
    }

    :deep(img) {
      max-width: 100%;
      height: auto;
      border-radius: 8px;
      margin: 20px 0;
    }

    :deep(ul),
    :deep(ol) {
      margin: 15px 0;
      padding-left: 30px;
    }

    :deep(li) {
      margin: 8px 0;
    }
  }

  .news-tags {
    margin-bottom: 30px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;

    h3 {
      margin: 0 0 15px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    .tags-list {
      .tag {
        display: inline-block;
        background: #f0f9ff;
        color: #1890ff;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 14px;
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }
  }
}

.news-sidebar {
  .related-news {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h3 {
      margin: 0 0 20px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    .related-list {
      .related-item {
        padding: 15px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: all 0.3s ease;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          background: #f8f9fa;
          border-radius: 4px;
          padding-left: 10px;
        }

        h4 {
          margin: 0 0 8px 0;
          color: #333;
          font-size: 14px;
          font-weight: 500;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .related-date {
          color: #999;
          font-size: 12px;
        }
      }
    }
  }
}

.loading-container,
.error-container {
  max-width: 1400px;
  margin: 50px auto;
  padding: 0 20px;
}

// 响应式设计
@media (max-width: 768px) {
  .news-content .container {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .news-main {
    padding: 20px;

    .news-title {
      font-size: 24px;
    }

    .news-meta {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;

      .meta-right {
        flex-wrap: wrap;
        gap: 15px;
      }
    }
  }

  .news-sidebar {
    order: -1;
  }
}
</style>
